/*
 * panelTowerInfo.java
 *
 * Created on November 26, 2007, 8:57 PM
 *
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package hextd.UI;

import com.usoog.tdcore.gamegrid.GridPoint;
import com.usoog.tdcore.message.MessageTowerSell;
import com.usoog.tdcore.message.MessageTowerUpgrade;
import com.usoog.tdcore.player.LocalPlayerListener;
import com.usoog.tdcore.player.Player;
import com.usoog.tdcore.player.PlayerListener;
import hextd.Constants;
import hextd.core.GameManagerImplementation;
import hextd.core.GameStateImplementation;
import hextd.tower.PanelTowerSettings;
import hextd.tower.HexTDTower;
import hextd.creep.HexTDCreep;
import hextd.creep.CreepChangeListener;
import hextd.creep.HexTDCreepData;
import hextd.tower.FactoryTower.type;
import hextd.util.Cache;
import hextd.util.TowerChangeListener;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

/**
 *
 * @author  hylke
 */
public class PanelTowerInfo
		extends javax.swing.JPanel
		implements LocalPlayerListener, PlayerListener, TowerChangeListener, CreepChangeListener {

	public static DecimalFormat form = new DecimalFormat("#,###.#");
	private GameManagerImplementation gameManager;
	private GameStateImplementation gameState;
	private HexTDTower selectedTower;
	private HexTDCreep selectedCreep;
	private HTMLEditorKit editorkit;
	private boolean selling = false;
	private PanelTowerSettings pts;
	private Player<HexTDCreepData, HexTDCreep, HexTDTower> localPlayer;

	/** Creates new form panelTowerInfo */
	public PanelTowerInfo() {
	}

	public void setContext(GameManagerImplementation gm) {
		gameManager = gm;
		gameState = (GameStateImplementation) gm.getGameState();
		gameManager.addLocalPlayerListener(this);
		initAll();
	}

	private void initAll() {
		if (!SwingUtilities.isEventDispatchThread()) {
			SwingUtilities.invokeLater(new Runnable() {

				@Override
				public void run() {
					initAll();
				}
			});
		} else {
			this.editorkit = new HTMLEditorKit();
			initComponents();
			jButton_confirmN.setVisible(false);
			jButton_confirmY.setVisible(false);
			jLabel_buttons.setVisible(false);

			StyleSheet s = Cache.getInstance().loadStyleSheet("styles.css");
			this.editorkit.setStyleSheet(s);
			jTextPane1.setEditorKit(this.editorkit);
		}
	}

	public void setTower(HexTDTower t) {
		unselectCreep();
		selling = false;
		if (t.getOwner() == localPlayer
				|| gameState.getGamePhase().getKey().equalsIgnoreCase("replaying")
				|| gameState.getGamePhase().getKey().equalsIgnoreCase("checking")) {
			unselectTower();
			selectedTower = t;
			t.setSelected(true);
			t.addTowerChangeListener(this);

			jPanel_towerSettings.removeAll();
			if (t.getType() != type.homeBase) {
				pts = t.getButtons();
				if (pts != null) {
					jPanel_towerSettings.add(pts);
				}
			}
			this.setVisible(true);
			this.updateInterface();
		}
	}

	public void setCreep(HexTDCreep s) {
		this.unselectTower();
		this.unselectCreep();
		this.selectedCreep = s;
		s.addStatusListener(this);
		s.setSelected(true);
		this.setText(s.getStatusString());
		this.setVisible(true);
	}

	public void setExternalText(String s) {
		if (!SwingUtilities.isEventDispatchThread()) {
			final String finalText = s;
			SwingUtilities.invokeLater(new Runnable() {

				@Override
				public void run() {
					setExternalText(finalText);
				}
			});
		} else {
			this.unselectCreep();
			this.unselectTower();
			this.selling = false;
			jPanel_buttons.setVisible(false);
			jPanel_towerSettings.removeAll();
			this.setText(s);
			this.setVisible(true);
		}
	}

	private String format(long number) {
		if (number > 1000) {
			return PanelTowerInfo.form.format(1f * number / 1000) + "K";
		} else {
			return "" + number;
		}
	}

	private void updateInterface() {
		Map<String, Long> tempCost = null;
		HexTDTower st;
		PanelTowerSettings settingsPanel;
		if (!SwingUtilities.isEventDispatchThread()) {
			SwingUtilities.invokeLater(new Runnable() {

				@Override
				public void run() {
					updateInterface();
				}
			});
		} else {
			if (selectedCreep != null) {
			} else {
				if (gameState.getGamePhase().getKey().equalsIgnoreCase("playing")) {

					if (selling) {
						jButton_sell.setVisible(false);
						jButton_upgrade.setVisible(false);
						jButton_confirmN.setVisible(true);
						jButton_confirmY.setVisible(true);
						jLabel_buttons.setVisible(true);
					} else {
						jButton_confirmN.setVisible(false);
						jButton_confirmY.setVisible(false);
						jLabel_buttons.setVisible(false);
						jButton_sell.setVisible(true);
						jButton_upgrade.setVisible(true);
					}

					st = selectedTower;
					settingsPanel = this.pts;
					if (st != null) {
						if (settingsPanel != null && !settingsPanel.isEnabled()) {
							settingsPanel.setEnabled(true);
						}
						if (!jPanel_buttons.isVisible()) {
							jPanel_buttons.setVisible(true);
						}
						boolean canUpgrade = st.canUpgrade("", true);
						tempCost = st.getUpgradeCost("", true, tempCost);
						Long credits = tempCost.get(Constants.RESOURCE_CREDIT);
						boolean canQueue = localPlayer.getResources().canQueue(st.getUpgradeCost("", true, tempCost));
						if (canUpgrade) {
							jButton_upgrade.setText(" ↥ (" + format(credits) + "€)");
							if (canQueue) {
								jButton_upgrade.setEnabled(true);
							} else {
								jButton_upgrade.setEnabled(false);
							}
						} else {
							jButton_upgrade.setEnabled(false);
							jButton_upgrade.setText(" ↥ (MAX)");
						}

						if (st.canBeSold()) {
							jButton_sell.setEnabled(true);
						} else {
							jButton_sell.setEnabled(false);
						}
						this.setText(st.getStatusString());
					} else {
						jPanel_buttons.setVisible(false);
					}

				} else {
					st = selectedTower;
					settingsPanel = pts;
					if (st != null) {
						jPanel_buttons.setVisible(false);
						setText(st.getStatusString());
						if (settingsPanel != null) {
							settingsPanel.setEnabled(false);
						}
					}

				}
			}
		}
	}

	private synchronized void setText(String s) {
		try {
			Document doc = jTextPane1.getDocument();
			doc.remove(0, doc.getLength());
			jTextPane1.setText("<html><body>" + s + "</body></html>");
		} catch (BadLocationException ex) {
			Logger.getLogger(PanelTowerInfo.class.getName()).log(Level.SEVERE, null, ex);
		} catch (NullPointerException ex) {
			Logger.getLogger(PanelTowerInfo.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public boolean hasSelectedTower() {
		return (selectedTower != null);
	}

	public void unselectTower() {
		HexTDTower st = selectedTower;
		selectedTower = null;

		this.setVisible(false);
		if (st != null) {
			st.setSelected(false);
			st.removeTowerChangeListener(this);
		}

		jPanel_towerSettings.removeAll();
	}

	public void unselectCreep() {
		if (selectedCreep != null) {
			selectedCreep.removeStatusListener(this);
			selectedCreep.setSelected(false);
			selectedCreep = null;
		}
	}

	public void upgradeCurrentTower(boolean fully) {
		HexTDTower st = selectedTower;
		if (fully) {
			if (st != null && localPlayer.getResources().canQueue(st.getUpgradeCost("full", true, null))) {
				GridPoint gl = st.getTile().getGridLocation();
				MessageTowerUpgrade messageTowerUpgrade = new MessageTowerUpgrade(-1, -1, gl.col, gl.row, "full");
				gameManager.addLocalplayerAction(messageTowerUpgrade);
			}
		} else {
			if (st != null && localPlayer.getResources().canQueue(st.getUpgradeCost("", true, null))) {
				GridPoint gl = st.getTile().getGridLocation();
				MessageTowerUpgrade messageTowerUpgrade = new MessageTowerUpgrade(-1, -1, gl.col, gl.row, "");
				gameManager.addLocalplayerAction(messageTowerUpgrade);
			}
		}

	}

	public void startSellCurrentTower() {
		HexTDTower st = selectedTower;
		if (st != null
				&& gameState.getGamePhase().getKey().equalsIgnoreCase("playing")
				&& st.canBeSold()) {
			this.selling = true;
			this.updateInterface();
		}

	}

	public boolean isSelling() {
		return selling;
	}

	public void confirmSell() {
		HexTDTower st = selectedTower;
		if (selling
				&& st != null
				&& gameState.getGamePhase().getKey().equalsIgnoreCase("playing")
				&& st.canBeSold()) {
			GridPoint gl = st.getTile().getGridLocation();
			MessageTowerSell messageTowerSell = new MessageTowerSell(-1, -1, gl.col, gl.row);
			gameManager.addLocalplayerAction(messageTowerSell);
			selling = false;
			unselectTower();
			updateInterface();
		}
	}

	public void cancelSell() {
		this.selling = false;
		this.updateInterface();
	}

	@Override
	public void localPlayerChanged(Player newLocalPlayer) {
		localPlayer.removePlayerListener(this);
		localPlayer = newLocalPlayer;
		localPlayer.addPlayerListener(this);
	}

	@Override
	public void resourcesChanged() {
		this.updateInterface();
	}

	@Override
	public void livesChanged(int newLives) {
	}

	@Override
	public void towerChanged() {
		updateInterface();
	}

	@Override
	public void enemySpriteStatusChanged() {
		setText(selectedCreep.getStatusString());
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jPanel_towerSettings = new javax.swing.JPanel();
        jPanel_buttons = new javax.swing.JPanel();
        jButton_upgrade = new javax.swing.JButton();
        jButton_sell = new javax.swing.JButton();
        jButton_confirmY = new javax.swing.JButton();
        jLabel_buttons = new javax.swing.JLabel();
        jButton_confirmN = new javax.swing.JButton();

        setBackground(Constants.colorBackGround);
        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Info", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12), Constants.colorForeGround)); // NOI18N
        setForeground(Constants.colorForeGround);
        setMaximumSize(new java.awt.Dimension(200, 2147483647));
        setMinimumSize(new java.awt.Dimension(200, 150));
        setPreferredSize(new java.awt.Dimension(200, 300));
        setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setBackground(Constants.colorBackGround);
        jScrollPane1.setBorder(null);
        jScrollPane1.setForeground(Constants.colorForeGround);

        jTextPane1.setBackground(Constants.colorBackGround);
        jTextPane1.setBorder(null);
        jTextPane1.setForeground(Constants.colorForeGround);
        jScrollPane1.setViewportView(jTextPane1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 0.01;
        gridBagConstraints.weighty = 0.01;
        add(jScrollPane1, gridBagConstraints);

        jPanel_towerSettings.setBackground(Constants.colorBackGround);
        jPanel_towerSettings.setForeground(Constants.colorForeGround);
        jPanel_towerSettings.setLayout(new java.awt.BorderLayout());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        add(jPanel_towerSettings, gridBagConstraints);

        jPanel_buttons.setBackground(Constants.colorBackGround);
        jPanel_buttons.setForeground(Constants.colorForeGround);
        jPanel_buttons.setLayout(new java.awt.GridBagLayout());

        jButton_upgrade.setBackground(Constants.colorBackGround);
        jButton_upgrade.setForeground(Constants.colorForeGround);
        jButton_upgrade.setText(" ↥ ");
        jButton_upgrade.setToolTipText("Upgrade");
        jButton_upgrade.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jButton_upgrade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_upgradeActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.weightx = 0.01;
        jPanel_buttons.add(jButton_upgrade, gridBagConstraints);

        jButton_sell.setBackground(Constants.colorBackGround);
        jButton_sell.setForeground(Constants.colorForeGround);
        jButton_sell.setText("↺");
        jButton_sell.setToolTipText("Recycle");
        jButton_sell.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jButton_sell.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_sellActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 0.01;
        jPanel_buttons.add(jButton_sell, gridBagConstraints);

        jButton_confirmY.setBackground(Constants.colorBackGround);
        jButton_confirmY.setForeground(Constants.colorForeGround);
        jButton_confirmY.setText("Y");
        jButton_confirmY.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_confirmYActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        jPanel_buttons.add(jButton_confirmY, gridBagConstraints);

        jLabel_buttons.setBackground(Constants.colorBackGround);
        jLabel_buttons.setForeground(Constants.colorForeGround);
        jLabel_buttons.setText("Confirm sale:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.weightx = 0.02;
        jPanel_buttons.add(jLabel_buttons, gridBagConstraints);

        jButton_confirmN.setBackground(Constants.colorBackGround);
        jButton_confirmN.setForeground(Constants.colorForeGround);
        jButton_confirmN.setText("N");
        jButton_confirmN.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_confirmNActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        jPanel_buttons.add(jButton_confirmN, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        add(jPanel_buttons, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents
    private void jButton_confirmYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_confirmYActionPerformed
		this.confirmSell();
    }//GEN-LAST:event_jButton_confirmYActionPerformed

    private void jButton_confirmNActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_confirmNActionPerformed
		this.cancelSell();
    }//GEN-LAST:event_jButton_confirmNActionPerformed

    private void jButton_sellActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_sellActionPerformed
		this.startSellCurrentTower();
    }//GEN-LAST:event_jButton_sellActionPerformed

    private void jButton_upgradeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_upgradeActionPerformed
		this.selling = false;
		this.upgradeCurrentTower(false);
    }//GEN-LAST:event_jButton_upgradeActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_confirmN;
    private javax.swing.JButton jButton_confirmY;
    private javax.swing.JButton jButton_sell;
    private javax.swing.JButton jButton_upgrade;
    private javax.swing.JLabel jLabel_buttons;
    private javax.swing.JPanel jPanel_buttons;
    private javax.swing.JPanel jPanel_towerSettings;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables
}
